package screen;

import java.util.Vector;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import main.GameCanvas;
import main.NuoiThuMidlet;
import model.Animal;
import model.AnimalInfo;
import model.Command;
import model.DataManager;
import model.IAction;
import model.Position;
import model.ToyInfo;
import service.GlobalService;
import utilities.CRes;
import utilities.GameResource;
import utilities.ImagePack;
import utilities.TileMap;
import animation.FlyText;
import animation.Smoke;

public class QuestPetScr extends PlayGameScr{
	static QuestPetScr instance;

	private Command clearPet;
	private Command setPet;
	private Command finishCmd;
	private Command shootCmd;
	
	private boolean m_bIsHidePet = false;
	private short m_sIsChangePlayer = 0;
	
	private int m_iTime;
	private int m_iSize;
	private int m_iSelectedRow;
	private int m_iSelectedCol;
	private int m_iCellSize;
	private int m_iPlayerInTurn;
	private int m_iAdding;
	
    int xTo = 0;
    public static int xLimit;
    public static int xCam = 0;
    private int m_iCurrentTime;
    
	public int m_iNumPet = 5;
	
	public byte[][] m_mydata;
	public byte[][] m_opdata;
	public int m_iCountAnimalHide = 0;
	
	private Image m_imgBox;
	private Image m_imgBackRoundGame;
	
	private AnimalInfo m_chicken;
	private AnimalInfo m_duck;
	
	public static void clean(){
		if(instance != null){
			instance.m_imgBox = null;
			instance.m_imgBackRoundGame = null;
			instance.m_imgBackground = null;
			instance.m_mydata = null;
			instance.m_opdata = null;
			instance.m_arrChatContent = null;
			instance.m_arrPlayers = null;
			instance.m_arrPos = null;
		}
		instance = null;		
	}
	
	public void switchToMe(byte roomID1, byte boardID, Vector vtPlayers,
			int ownerID, int money) {
		// TODO Auto-generated method stub
		m_bIsHidePet = false;
		super.switchToMe(roomID1, boardID, vtPlayers, ownerID, money);
	}
	
	public QuestPetScr(int maxPlayer) {
		super(maxPlayer);
		// TODO Auto-generated constructor stub
		m_chicken = DataManager.gI().getAnimalInfo(1);
		m_duck = DataManager.gI().getAnimalInfo(2);
		
		m_bIsDisplayAnimal = false;//game nay khong can ve con thu
		
		TileMap.instance.loadMap(TileMap.QUEST_PET_MAP);        
		
		m_arrPos[0] = new Position(10, GameCanvas.h - 100);
		m_arrPos[0].anchor = 0;
		
		m_arrPos[1] = new Position(GameCanvas.w - 70, m_arrPos[0].y);
		m_arrPos[1].anchor = 1;
				
		m_iSize = 5;
		m_iCellSize = 32;
		m_iAdding = 5;
		
    	m_width = (m_iCellSize + m_iAdding) * m_iSize;
        m_height = m_width;
    	m_left = (GameCanvas.w - m_width) >> 1;
    	m_top = (GameCanvas.h - m_height) >> 1 ;
    	
    	xLimit = -GameCanvas.w;
    	/////////////
    	/////////
		m_imgBackRoundGame = Image.createImage(GameCanvas.w, GameCanvas.h);
		
		Graphics g = m_imgBackRoundGame.getGraphics();
		TileMap.instance.paintMap(g, 0, 0);	
		int tmp = m_left+m_width;		
		g.drawImage(GameResource.instance.imgBigTree, m_left + 10, m_top - 5, Graphics.BOTTOM|Graphics.HCENTER);
		g.drawImage(GameResource.instance.imgBigTree, 600, m_top - 10, Graphics.BOTTOM|Graphics.HCENTER);
		
		g.drawImage(GameResource.instance.imgFance, tmp, m_top - 15, Graphics.BOTTOM|Graphics.HCENTER);
		g.drawImage(GameResource.instance.imgFance, tmp + GameResource.instance.imgFance.getWidth(), m_top - 15, Graphics.BOTTOM|Graphics.HCENTER);
		
		g.drawImage(GameResource.instance.imgFance, tmp + 250, m_top-25, Graphics.BOTTOM|Graphics.HCENTER);
		g.drawImage(GameResource.instance.imgFance, tmp + 80, m_top-30, Graphics.BOTTOM|Graphics.HCENTER);
		
		ToyInfo t = DataManager.gI().getToyInfo(4);
		if(t != null)
			t.paintIcon(g, tmp+35, m_top-35);
		t = DataManager.gI().getToyInfo(1);
		if(t != null){			
			t.paintIcon(g, tmp+150 , m_top-25);
		}
		
		////////
		tmp = m_top + m_height;
		g.drawImage(GameResource.instance.imgFance, m_left+10, tmp + 45, Graphics.BOTTOM|Graphics.HCENTER);
		g.drawImage(GameResource.instance.imgFance, m_left+10+GameResource.instance.imgFance.getWidth(), tmp + 45, Graphics.BOTTOM|Graphics.HCENTER);
		int a = m_left+m_width;		 
		g.drawImage(GameResource.instance.imgFance, a+250, tmp+50, Graphics.BOTTOM|Graphics.HCENTER);
		g.drawImage(GameResource.instance.imgFance, a+80, tmp+60, Graphics.BOTTOM|Graphics.HCENTER);
		
		t = DataManager.gI().getToyInfo(2);
		if(t != null)
			t.paintIcon(g, a+20, tmp+10);
		t = DataManager.gI().getToyInfo(3);
		if(t != null){			
			t.paintIcon(g, a+50, tmp+20);
		}
		t = null;
		/////////////
		m_imgBox = ImagePack.createImage(41);
    	
    	setPet = new Command("Đặt", new IAction() {
			public void perform() {
				// TODO Auto-generated method stub
				m_mydata[m_iSelectedRow][m_iSelectedCol] = 1;
				m_iCountAnimalHide++;
			}
		});
    	
    	clearPet = new Command("Bỏ", new IAction() {
			public void perform() {
				// TODO Auto-generated method stub
				m_mydata[m_iSelectedRow][m_iSelectedCol] = 0;
				m_iCountAnimalHide--;
			}
		});
    	
    	finishCmd = new Command("Xong", new IAction() {
			public void perform() {
				// TODO Auto-generated method stub
				//submit to server
				GlobalService.gI().submitPetPos(m_iRoomID, m_iBoardID, m_mydata, m_iNumPet);
				
				m_cmdCenter = null;
				m_cmdRight = null;
				m_bIsHidePet = false;
			}
		});
    	
    	shootCmd = new Command("Đoán", new IAction() {
			public void perform() {
				// TODO Auto-generated method stub
				GlobalService.gI().shoot(m_iRoomID, m_iBoardID, m_iSelectedRow, m_iSelectedCol);
				m_cmdCenter = null;
				m_cmdRight = null;
			}
		});
	}

    public static QuestPetScr gI() {
        if (instance == null) {
            instance = new QuestPetScr(2);
        }
        return instance;
    }
    
    public void onStartGame(int timeHidePet, int numPet){
    	startGame();
    	
    	m_bIsHidePet = true;
    	m_iTime = timeHidePet;
    	m_iSelectedCol = 0;
    	m_iSelectedRow = 0;
    	xTo = 0;
    	m_iCountAnimalHide = 0;
    	
    	m_iNumPet = numPet;
    	m_mydata = null;
    	m_opdata = null;
    	
    	m_mydata = new byte[m_iNumPet][m_iNumPet];
    	m_opdata = new byte[m_iNumPet][m_iNumPet];
    	
    	
    	//clear data
    	//0: chua dat thu
    	//1: dat roi
    	//2: bi chet
    	int i, j;
    	for(i = 0; i < m_iNumPet; i++){
    		for(j = 0; j < m_iNumPet; j ++){
    			m_mydata[i][j] = 0;
    			m_opdata[i][j] = 0;
    		}
    	}
    	
    	m_cmdCenter = setPet;
    	m_cmdRight = null;
    	m_bEndGame = false;
    	GameCanvas.endDlg();
    }
    
    public void paint(Graphics g){
    	g.translate(-g.getTranslateX(), -g.getTranslateY());
		g.setClip(0, 0, GameCanvas.w, GameCanvas.h);

        g.drawImage(m_imgBackRoundGame, 0, 0, 0); 
    	if (xCam != xTo) {
            cmvy = (xTo - xCam) << 1;
            cmdy += cmvy;
            xCam += cmdy >> 4;
            cmdy = cmdy & 0xf;
            if (xCam < xLimit) {
                xCam = xTo = xLimit;
            }
            if (xCam > 0) {
                xCam = xTo = 0;
            }
        }
        g.translate(xCam, 0);       
        
        //////////////
        if(isPlaying()){   		    		   		
        	//paint player info
        	for(int i = 0; i < m_iMaxPlayer; i++){
    			if(m_arrPlayers[i].m_iId != NuoiThuMidlet.m_myPlayerInfo.m_iId){	
    				m_arrPlayers[i].paintAvatarInBoard(g, GameCanvas.w - 67 - xCam, 5, 75 , 40);
    				break;
    			}
    		}
            NuoiThuMidlet.m_myPlayerInfo.paintAvatarInBoard(g, 2 - xCam, 5, 75, 40);
    		
        	//paint ban co 5*5    		
			int i, j, tmp;
			for(i = 0; i < m_iSize; i++){//for theo row
				tmp = i * (m_iCellSize + m_iAdding);
				for(j = 0; j < m_iSize; j++){//for theo col
					//paint my board
					if(m_mydata[i][j] == 0)
						g.drawImage(m_imgBox, m_left + j * (m_iCellSize + m_iAdding), m_top + tmp, 0);
					else{
						int xPos = m_left + j * (m_iCellSize + m_iAdding);
						int yPos = m_top + tmp + (m_iCellSize + m_iAdding);
						
						if(m_mydata[i][j] == 2){//bi trung dan							
							m_chicken.paintAction(g, 1, Animal.SLEEP, xPos, yPos, 0);
						}
						else if(m_mydata[i][j] == 1){//o co thu
							m_chicken.paintAction(g, 1, Animal.STAND, xPos, yPos, 0);
						}
					}						
					
					//paint opponent board
					if(m_opdata[i][j] == 0)
						g.drawImage(m_imgBox,  GameCanvas.w + m_left + j * (m_iCellSize + m_iAdding), m_top + tmp, 0);
					else{
						int xPos = GameCanvas.w + m_left + j * (m_iCellSize + m_iAdding);
						int yPos = m_top + tmp + (m_iCellSize + m_iAdding);
						
						if(m_opdata[i][j] == 2){//bi trung dan						
							m_duck.paintAction(g, 1, Animal.SLEEP, xPos, yPos, 0);
						}
						else if (m_opdata[i][j] == 1){//o co thu
							m_duck.paintAction(g, 1, Animal.STAND, xPos, yPos, 0);
						}
					}
				}
			}
			
			GameResource.instance.m_frameIconItems.drawFrame(19,  m_left - xTo + m_iSelectedCol * (m_iCellSize + m_iAdding), m_top + m_iSelectedRow * (m_iCellSize + m_iAdding), Sprite.TRANS_NONE, g);
							
			if(!m_bEndGame){
				if(m_sIsChangePlayer == 0){	
					PaintPopup.paintBoxClock(g, 5 - xCam, 38, "" + m_iTime);
				}
				else{
					PaintPopup.paintBoxClock(g, GameCanvas.w - 65 - xCam, 38, "" + m_iTime);
				}
			}
			else{
				PaintPopup.paintBoxClock(g, GameCanvas.hw - xCam, 38, "" + m_iTime);
			}
    	}
                
   		super.paint(g);
    }
    
    public void updateKey(){
    	if(isPlaying()){
    		if (GameCanvas.isPointerClick) {  
    			int posY = m_iSelectedRow * (m_iCellSize + m_iAdding) + m_top + 10;
    			int posX = m_left + (m_iSelectedCol) * (m_iCellSize + m_iAdding) + 10;
    			
    			if(GameCanvas.isPointer(posX, posY, m_iCellSize, m_iCellSize)){
    				if(m_cmdCenter != null)
    					m_cmdCenter.action.perform();
    				return;
    			}
    			else
    			{
    				int i, j, tmp;
    				for(i = 0; i < m_iSize; i++){//for theo row
    					tmp = i * (m_iCellSize + m_iAdding);
    					for(j = 0; j < m_iSize; j++){//for theo col
    						posX = m_left + j * (m_iCellSize + m_iAdding);
							posY = m_top + tmp;
							if(GameCanvas.isPointer(posX, posY, m_iCellSize, m_iCellSize)){
								m_iSelectedCol = j;
								m_iSelectedRow = i;
								return;
							}
    					}
    				}
    			}
        	}
    	
        	if (GameCanvas.keyPressed[8]) {

        		m_iSelectedRow++;
        		if(m_iSelectedRow >= m_iSize)
        			m_iSelectedRow = 0;
            	GameCanvas.keyPressed[8] = false;

        	} else if (GameCanvas.keyPressed[2]) {

        		m_iSelectedRow--;
        		if(m_iSelectedRow < 0)
        			m_iSelectedRow = m_iSize - 1;       		
        		
        		GameCanvas.keyPressed[2] = false;

        	} else if (GameCanvas.keyPressed[4]) {
        		m_iSelectedCol--;
        		if(m_iSelectedCol < 0)
        			m_iSelectedCol = m_iSize - 1;
        		GameCanvas.keyPressed[4] = false;

        	} else if (GameCanvas.keyPressed[6]) {
        		m_iSelectedCol++;
        		if(m_iSelectedCol >= m_iSize)
        			m_iSelectedCol = 0;
        		GameCanvas.keyPressed[6] = false;
        	}
    	}
    	
        super.updateKey();
    }
 
    public void update(){
    	if(isPlaying()){
    		if(m_bIsHidePet){
        		m_cmdCenter = setPet;
        		if(m_mydata[m_iSelectedRow][m_iSelectedCol] == 1){
        			m_cmdCenter = clearPet;
        		}    		
        		if(m_iCountAnimalHide == m_iNumPet && m_mydata[m_iSelectedRow][m_iSelectedCol] == 0)
        			m_cmdCenter = finishCmd;
        	}
    		else if(m_bEndGame){
        		if(m_iTime <= 0){
        			xTo = 0;		
    				stopGame();
    				GameCanvas.endDlg();
        		}
        	}
    		else{
	    		if(m_iCurrentTime == 100){
	    			setNextPlayer(m_iPlayerInTurn);
	    			m_iTime = m_interval;
	    			m_sIsChangePlayer = (short) ((m_sIsChangePlayer+1)%2);
	    		}
    		}
    		m_iCurrentTime++;
    		if(m_iCurrentTime % 20 == 0 && m_iTime > 0)
    			m_iTime--;
    	}    	
    	super.update();
    }

    private short m_interval = 0;
	public void onBeginQuest(int playerID, short interval) {
		// TODO Auto-generated method stub
		m_bIsHidePet = false;
		m_iTime = interval;
		m_interval = interval;
		m_cmdRight = null;
		m_cmdCenter = null;
		m_cmdLeft = menuNormalCmd;
		
		setNextPlayer(playerID);
	}

	public void setNextPlayer(int playerId){
		if(!m_bEndGame){
			m_iPlayerInTurn = playerId;
			if(m_iPlayerInTurn == NuoiThuMidlet.m_myPlayerInfo.m_iId){
				m_cmdCenter = shootCmd;
				xTo = -GameCanvas.w;
			}
			else
			{
				m_cmdCenter = null;
				xTo = 0;
			}
		}
	}

	public void onShoot(int playerShoot,int row, int col, byte result, int nextPlayer) {
		// TODO Auto-generated method stub
		FlyText f = new FlyText();
		String text;
		boolean flag = true;
		if(result == 1){
			if(playerShoot != NuoiThuMidlet.m_myPlayerInfo.m_iId){
				//doi thu ban minh
				m_mydata[row][col] = 2;
			}
			else
			{
				//minh ban trung
				m_opdata[row][col] = 2;
			}
			
			text = "Trúng";
		}
		else{
			text = "Hụt";
			if(playerShoot == NuoiThuMidlet.m_myPlayerInfo.m_iId){
				//doi thu ban minh
				if(m_opdata[row][col] != 2){
					m_opdata[row][col] = 3;	
				}
				else{
					text = "Thú này đã được đoán";
					flag = false;
				}
			}
			else
			{
				if(m_mydata[row][col] != 2)
					m_mydata[row][col] = 3;
				else{
					text = "Thú này đã được đoán";
					flag = false;
				}
			}
				
		}
		
		int posY = row * (m_iCellSize + m_iAdding) + m_top + 10;
		int posX = m_left + (col) * (m_iCellSize + m_iAdding) + 10;
				
		f.startEffect(text, posX, posY, 0x00ff00, 0x000000);		
		
		if(flag){
			Smoke s = new Smoke();
			s.startEffect(posX, posY, 0, 0, Smoke.SMOKE);

			s = new Smoke();
			s.startEffect(posX, posY, CRes.random(4), CRes.random(-8, -5), Smoke.ROCK_2);
			s = new Smoke();
			s.startEffect(posX, posY, CRes.random(4), CRes.random(-8, -5), Smoke.ROCK_2);
			s = new Smoke();
			s.startEffect(posX, posY, CRes.random(4), CRes.random(-8, -5), Smoke.ROCK_2);	
		}
		
		
		//set next player
		m_iCurrentTime = 0;
		m_iPlayerInTurn = nextPlayer;
		
		/////////////     
    }

	public void onEndGame(int playerId) {
		// TODO Auto-generated method stub
		m_bEndGame = true;
		m_iIdWinner = playerId;
		m_iCurrentTime = 0;
		m_iTime = 5;
		
		String m_str= "";
		if(playerId == NuoiThuMidlet.m_myPlayerInfo.m_iId){
			if(m_iMoney > 0){
				int money = (m_iMoney*2 - m_iMoney/5);
				m_str = "Bạn đã chiến thắng! \n Bạn được: "+money;
			}
			else
				m_str = "Bạn đã chiến thắng!";
		}
		else{
			if(m_iMoney > 0){
				m_str = "Bạn đã thua! \n Bạn bị trừ: "+m_iMoney;
			}
			else{
				m_str = "Bạn đã thua!";
			}
		}
		GameCanvas.startOK(m_str, new IAction() {
			
			public void perform() {
				// TODO Auto-generated method stub
				xTo = 0;		
				
				stopGame();
				
				GameCanvas.endDlg();
			}
		});
		m_bIsHidePet = false;
		for(int i = 0; i < m_arrPlayers.length; i++){
			if(m_arrPlayers[i] != null && m_arrPlayers[i].m_iId != m_iOwnerID)
				m_arrPlayers[i].isReady = false;
		}
		
	}

	public void onNextTurn(int playerId) {
		// TODO Auto-generated method stub
		//setNextPlayer(playerId);
		m_iCurrentTime = 0;
		m_iPlayerInTurn = playerId;
	}

	public void onChatFromMe(String text) {
		// TODO Auto-generated method stub
		super.onChatFromMe(text);
	}
}
